<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { userUploadAvatarService } from '@/api/user'
import { useUserStore } from '@/stores'
const imgUrl = ref('')
const UserStore = useUserStore()
const renderAvatar = () => {
  imgUrl.value = UserStore.userinfo.user_pic
}
renderAvatar()
const onSelectFile = (uploadFile) => {
  const render = new FileReader()
  render.readAsDataURL(uploadFile.raw)
  render.onload = () => {
    imgUrl.value = render.result
  }
}

const avatarRefs = ref(null)

const onUpdateAvatar = async () => {
  await userUploadAvatarService(imgUrl.value)
  await UserStore.getUserInfoService()
  ElMessage({ type: 'success', message: '更换头像成功' })
}
</script>
<template>
  <div class="main1">
    <page-container title="更换头像">
      <el-upload
        ref="avatarRefs"
        class="avatar-uploader"
        :auto-upload="false"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :on-change="onSelectFile"
      >
        <img v-if="imgUrl" :src="imgUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <br />
      <el-button
        type="primary"
        :icon="Plus"
        size="large"
        @click="avatarRefs.$el.querySelector('input').click()"
        >选择头像</el-button
      >
      <el-button
        type="success"
        :icon="Upload"
        size="large"
        @click="onUpdateAvatar"
        >上传头像</el-button
      >
    </page-container>
  </div>
</template>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
